package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.ApiConstant;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author : xiongke
 * @Description:
 * @Date: 2024/8/29
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Resource
    WeChatProperties weChatProperties;
    @Resource
    JwtProperties jwtProperties;
    @Resource
    private UserMapper userMapper;

    @Override
    public UserLoginVO wxLogin(UserLoginDTO dto) {
        //调用http发送wx接口返回openID
        String openid = getOpenid(dto.getCode());
        User user = userMapper.queryByOpenid(openid);
        if (user == null) {
            //自动注册
            user = User.builder().openid(openid).createTime(LocalDateTime.now()).build();
            userMapper.save(user);
        }
        //生产jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        return UserLoginVO.builder().openid(openid).token(token).id(user.getId()).build();
    }

    private String getOpenid(String code){
        Map<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(ApiConstant.WX_LOGIN_API, map);
        //解析json数据为对象
        JSONObject jsonObject = JSON.parseObject(json);
        //获取openid
        return jsonObject.getString("openid");
    }
}
